package com.zhuang.singleton.type6;

/**
 * @Classname SingletonTest06
 * @Description  双重检查，推荐使用
 * @Date 2021/3/17 9:54
 * @Created by dell
 */

public class SingletonTest06 {
    public static void main(String[] args) {
        System.out.println("懒汉式，双重检查，推荐使用");
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        //判断是否为单例
        System.out.println(instance == instance2);
        System.out.println("intstance的哈希值" + instance.hashCode());
        System.out.println("intstance2的哈希值" + instance2.hashCode());
    }
}

class Singleton {
    private static volatile Singleton instance;

    private Singleton() {

    }

    //提供一个静态的公有方法，加入双重检查代码，加入同步处理的代码，解决懒加载的问题
    //保证效率。推荐使用
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                instance = new Singleton();
            }
        }
        return instance;
    }
}